package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;
    @Override
    public List<Address> findList(){
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        return addressMapper.selectList(wrapper);
    }



    @Override
    public void save(Address address) {
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0);//设置为非默认地址

        //2. 保存
        addressMapper.insert(address);
    }
    @Override
    public void setDefault(Long id){
        //全部设置为非默认
        Address address = new Address();
        address.setIsDefault(0);
        //设置更新条件
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId());

        //更新
        addressMapper.update(address,wrapper);

        //设置默认地址
        address.setIsDefault(1);
        address.setId(id);
        addressMapper.updateById(address);
    }
    @Override
    public Address findDefault(){

        LambdaQueryWrapper<Address>wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId());
        wrapper.eq(Address::getIsDefault,1);//查询是否有默认地址
        return addressMapper.selectOne(wrapper);
    }

}
